import React, {useState, FC, useEffect} from "react";
import {TimerProps, TimerResult} from '../../types/timer'
import {minuteToTime, quickSort, formatDate} from '../../util'
import './style.css'

interface HalfHourBlogProps extends TimerProps {
	index: number,
	weekKey: string,
	timerInfo: TimerResult[]
}

const HalfHourBlog: FC<HalfHourBlogProps> = (props: HalfHourBlogProps) => {
	const {index, width, themeColor, weekKey, timerInfo, changeTimer, canBeClear} = props
	const [checked, setChecked] = useState<boolean>(false);
	/**
	 * 点击【半小时】格子
	 * @param e
	 * @param weekKey 当前对应的星期
	 */
	const halfHourClick = (e: any, weekKey: string) => {
		const HALF_HOUR_TIME = 30 * 60 * 1000;
		const time = new Date(`2021-01-01 ${minuteToTime((index + 1) * 30)}`).getTime();
		setChecked((oldValue) => !oldValue)
		// 当前星期所对应的信息
		const current: TimerResult | undefined = timerInfo.find(item => item.key === weekKey)
		// 查找当前星期中是否存在选过的时间
		const result = current!.timeRanges.find(item => item === time)
		const timeRanges = current!.timeRanges;
		if (!result) {
			timeRanges.push(time);
		} else {
			timeRanges.splice(timeRanges.findIndex(item => item === time), 1)
		}
		const sortResult = quickSort(timeRanges)
		current!.timeRanges = sortResult;
		const yyy = []
		for (let i = 0; i < sortResult.length; i++) {
			if (sortResult[i + 1] - sortResult[i] > HALF_HOUR_TIME) {
				yyy.push(i)
			}
		}
		yyy.push(sortResult.length - 1)
		let key = 0
		current!.resultShow = []
		yyy.forEach(item => {
			if (sortResult[key]) {
				current!.resultShow.push(formatDate(sortResult[key] - 30 * 60 * 1000) + "~" + formatDate(sortResult[item]))
			}
			key = item + 1
		})
		if (changeTimer) {
			changeTimer(timerInfo)
		}
	}
	return (
		<div
			onClick={(e) => halfHourClick(e, weekKey)}
			className='half_hour'
			style={{
				backgroundColor: checked ? themeColor : "transparent",
				width: (width! - 64 - 48) / 48
			}}
		/>
	)
}
export default HalfHourBlog